package top.kent90.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;

/**
 *  处理登录的拦截器
 * @author kent
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 预处理，先于controller执行，返回true为放行请求，再到下一个拦截器，
	 * 如果没有可执行的拦截器，再到controller进行处理
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("我是preHandle");
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("UserInfo");
		if(obj==null) {
			request.setAttribute("msg", "请登录！");
			request.getRequestDispatcher("/index.jsp").forward(request,response);
			return false;
		}
		return true;
	}

	/**
	 *    怎么处理ajax请求
	 */
	@Override
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView model)
			throws Exception {
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("UserInfo");
		if(obj==null) {
			model.addObject("msg", "请登录！");
			model.setViewName("../../index");
		}
	}

	/**
	 * controller处理完成之后，再经过此方法
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
		System.out.println("我是afterCompletion");
	}
}